/**
 * @author		Sergey Suzdalskiy
 * @e-mail:		sergey.suzdalskiy@gmail.com
 */
package ua.kiev.gcore.net.config
{
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	
	
	

	public class ConfigLoader extends EventDispatcher
	{	
		public var url:String;
		private var configLoader:URLLoader;
		
		public var data:Object;
		
		public function ConfigLoader(){
			data = new Object();
		}
		
		
		public function load(configURL:String):void{	
			url = configURL;
			configLoader = new URLLoader();
			configLoader.dataFormat = URLLoaderDataFormat.TEXT;
			configLoader.addEventListener(Event.COMPLETE, loadJSONHandler);
			configLoader.addEventListener(IOErrorEvent.IO_ERROR, loadJSONIOError);
			configLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loadJSONSecurityError);
			try{
				configLoader.load(new URLRequest(url));
			}catch(error:Error){
				data = '{"error":{"type":"' + error.name + '","msg":"' + error.message + '"}}';
				dispatchEvent(new Event(Event.COMPLETE))
			}
		}
		
		private function loadJSONHandler(event:Event):void{				
			data = configLoader.data;
			dispatchEvent(new Event(Event.COMPLETE))
		}
		
		private function loadJSONSecurityError(event:SecurityErrorEvent):void{
			data = '{"error":{"type":"SecurityError","msg":"' + event.text +'"}}';
			dispatchEvent(new Event(Event.COMPLETE))
		}
		
		private function loadJSONIOError(event:IOErrorEvent):void{
			data = '{"error":{"type":"IOError","msg":"' + event.text +'"}}';
			dispatchEvent(new Event(Event.COMPLETE))
		}
		
		
		
	}
}